package com.jusfoun.communication.service;

import com.jusfoun.communication.dao.AppInfoDao;
import com.jusfoun.communication.model.AppInfo;
import com.jusfoun.communication.model.User;
import com.jusfoun.communication.util.PageInfo;
import com.jusfoun.communication.util.Result;
import com.jusfoun.communication.util.ResultUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 系统管理service
 *
 * @author player six
 * @email jslcylcy@163.com
 * @create 2017-10-12 11:10
 **/
@Service
public class ManageService {

    @Autowired
    private ResultUtil resultUtil;

    @Autowired
    private UserService userService;

    @Autowired
    private AppInfoDao appInfoDao;

    private static final Logger logger = LoggerFactory.getLogger(ManageService.class);

    /**
     * 向系统中新增app 生成appId 与 appSecret
     *
     * @param appInfo
     */
    public Result addApp(AppInfo appInfo) {
        //生成appId
        String appId = null;
        synchronized (ManageService.class) {
            long currentTime = System.currentTimeMillis();
            appId = Long.toString(currentTime, 36);
        }
        if (null != appId) {
            String appSecret = DigestUtils.md5Hex(UUID.randomUUID().toString());
            appInfo.setAppId(appId);
            appInfo.setAppSecret(appSecret);
            appInfoDao.add(appInfo);
            logger.info("生成app,appID:" + appId);
            return resultUtil.success("成功", "新增app成功", appInfo);
        } else {
            return resultUtil.fail("失败", "生成appId失败");
        }
    }

    /**
     * 向系统中重新生成appSecret
     *
     * @param appInfo
     * @return
     */
    public Result generateSecret(AppInfo appInfo) {
        Long rank = appInfoDao.appRank(appInfo.getAppId());
        if (null == rank || rank < 0) {
            return resultUtil.fail("失败", "不存在的appId");
        } else {
            String appSecret = DigestUtils.md5Hex(UUID.randomUUID().toString());
            appInfo.setAppSecret(appSecret);
            appInfoDao.update(appInfo);
            logger.info("appID:" + appInfo.getAppId() + ",重新生成appsecret");
            return resultUtil.success("成功", "重新生成appSecret成功", appInfo);
        }
    }

    /**
     * 获取分页的app 列表
     *
     * @param page
     * @param rows
     * @return
     */
    public PageInfo<AppInfo> list(Integer page, Integer rows) {
        long total = appInfoDao.listIdCount();
        if (total > 0) {
            PageInfo<AppInfo> appInfoPageInfo = new PageInfo<>(page, rows, total);
            List<String> idList = appInfoDao.listId(appInfoPageInfo);
            List<AppInfo> list = new ArrayList<>();
            if (null != idList && !idList.isEmpty()) {
                for (String appId : idList) {
                    list.add(appInfoDao.getById(appId));
                }
            }
            return new PageInfo<>(list, page, rows, total);
        } else {
            return new PageInfo<>();
        }
    }

    /**
     * 获取所有的app 列表
     *
     * @return
     */
    public List<AppInfo> listAll() {
        return appInfoDao.listAll();
    }

    /**
     * 给指定用户生成token
     *
     * @param user
     * @return
     */
    public Result generateToken(User user) {
        if (appInfoDao.checkAppIdAndSecret(user.getAppId(), user.getAppSecret())) {
            if (StringUtils.isBlank(user.getUserName())) {
                return resultUtil.fail("失败", "用户名不能为空");

            }
            String token = userService.generateToken(user);
            userService.addUser2List(user);
            logger.info("用户appId:" + user.getAppId() + ",userName:" + user.getUserName() + ",生成token");
            return resultUtil.success("成功", "生成token成功", token);
        }
        return resultUtil.fail("失败", "secret与id不匹配");
    }

    /**
     * 校验appId与appSecret
     *
     * @param appId
     * @param appSecret
     * @return
     */
    public boolean checkAppIdAndSecret(String appId, String appSecret) {
        return appInfoDao.checkAppIdAndSecret(appId, appSecret);
    }

}
